package com.atguigu.gulimall.product.exception;

import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhuguanming
 * @date 2021/4/16
 */
@RestControllerAdvice(basePackages = "com.atguigu.gulimall.product.controller")
@Slf4j
public class GulimallExceptionControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R handleValidException(MethodArgumentNotValidException exception) {
        log.error("数据校验出现异常：{}，异常类型：{}", exception.getMessage(), exception.getClass(), exception);
        Map<String, FieldError> fieldErrorsMap = exception.getBindingResult().getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, a -> a, (o1, o2) -> o1));
        Map<String, String> fieldErrors = new HashMap<>(16);
        fieldErrorsMap.forEach((key, value) -> fieldErrors.put(key, value.getDefaultMessage()));
        return R.error(BizCodeEnum.VALID_EXCEPTION).put("data", fieldErrors);
    }

    @ExceptionHandler(value = Exception.class)
    public R handleAllException(Exception exception) {
        log.error("异常信息：{}", exception.getMessage(), exception);
        return R.error(BizCodeEnum.UNKNOW_EXCEPTION);
    }

}
